//
//  JobSubMViewController.m
//  ERP
//
//  Created by QA on 15/11/13.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "JCSubMViewController.h"
#import "CustomBadge.h"

#import "MJRefresh.h"
#import "JCSubMViewCell.h"
#import "UITableView+Custom.h"
#import "NSDictionary+DataFormat.h"
#import "JCSubMDetailViewController.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"

@interface JCSubMViewController ()

@property (strong, nonatomic) NSMutableArray *resultData;
@property (assign, nonatomic) NSInteger segmentActionState;

@end

@implementation JCSubMViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"辅材审核"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    
    self.tableView.tableFooterView= [[UIView alloc] init];
    [self.segmentedControl setTintColor:ThemeColorBlue];
    [self.segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self setupRefresh];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger index = Seg.selectedSegmentIndex;
    self.segmentActionState = index;
    
    [self.resultData removeAllObjects];
    [self.tableView reloadData];
    [self.tableView headerBeginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //@审核状态（待审核，已通过，已拒绝）
    NSString *RWDZTString = nil;
    if (self.segmentActionState == 0) {
        RWDZTString = [NSString stringWithFormat:@"待审核"];
    } else if (self.segmentActionState == 1) {
        RWDZTString = [NSString stringWithFormat:@"已通过"];
    } else if (self.segmentActionState == 2) {
        RWDZTString = [NSString stringWithFormat:@"已拒绝"];
    }
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"FCGL_SQD_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"状态" value:RWDZTString];
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0){
            firstArray = [result.resultArray firstObject];
        }
        
        //显示数据处理
        if(isReresh) [self.resultData removeAllObjects];
        if(firstArray && firstArray.count > 0){
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无辅材审核" isShow:YES];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"JCSubMViewCell";
    JCSubMViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[JCSubMViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSDictionary *itemData  = [self.resultData objectAtIndex:indexPath.row];
    
    //订单信息设置
    cell.gcmcLabel.text = [itemData objectFormatStringForKey:@"项目名称" defaults:@"未知"];
    cell.gmfsLabel.text = [itemData objectFormatStringForKey:@"购买方式" defaults:@"未知"];
    cell.sqsjLabel.text = [itemData objectFormatStringForKey:@"申请时间" defaults:@"未知"];;
    cell.ztLabel.text = [itemData objectFormatStringForKey:@"状态" defaults:@"未知"];
    cell.tjrLabel.text = [itemData objectFormatStringForKey:@"申请人" defaults:@"未知"];
    cell.jbzLabel.text = [itemData objectFormatStringForKey:@"申请站点" defaults:@"未知"];
    
    //订单是否已读
    NSInteger state = [itemData objectFormatIntegerForKey:@"ZT"];
    if(state != 0){
        cell.iconRead.hidden = YES;
        cell.jmNumLabel.text = [itemData objectFormatStringForKey:@"编号" defaults:@"未知"];
    } else {
        cell.iconRead.hidden = NO;
        cell.jmNumLabel.text = [itemData objectFormatStringForKey:@"编号" format:@"        %@" defaults:@"        未知"];
    }
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 82;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.row];
    JCSubMDetailViewController *mOrderDetails = [[JCSubMDetailViewController alloc] initWithValue:itemData];
    mOrderDetails.backResultDelagate = self;
    [self.navigationController pushViewController:mOrderDetails animated:YES];
    
}

#pragma mark
#pragma mark - BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    if (backValue && [backValue isKindOfClass:[NSDictionary class]]) {
        NSInteger index = [self.resultData indexOfObject:backValue];
        if (index < self.resultData.count) {
            [self.resultData removeObjectAtIndex:index];
            [self.tableView reloadData];
        }
        if(self.resultData.count <= 0)
        [self.tableView setTableViewNotDataDrawText:@"暂无辅材审核" isShow:YES];
    }
}

@end
